<?php
/**
 * This file is part of the Yacms (http://www.yacms.org)
 * Copyright (c) 2019 gylr0505 (http://www.yacms.org)
 *
 * Author: 鬼一浪人 <gylr0505@163.com>
 *
 * DateTime: 19-10-29 下午9:52
 * Description:
 */
 
declare(strict_types = 1);

namespace App\Template\Log;

use App\Model\Entity\TemplateSendLog;
use Carbon\Carbon;
use Swoft\Redis\Redis;

class Sync
{
    use LogTrait;

    private $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

    /**
     * 将缓存中的日志记录到数据库
     */
    public function execute()
    {
        $data = Redis::hGetAll($this->generatorLastCacheHashKey());
        if (!$data){
            return;
        }
        $data['successTotal'] = $data['success'] ?? 0;
        $data['failTotal'] = $data['fail'] ?? 0;
        $data['total'] = $data['successTotal'] + $data['failTotal'];
        $data['templateId'] = $this->id;

        try{
            Redis::del($this->generatorLastCacheHashKey());
            TemplateSendLog::query()->insert($data);
        }catch (\Exception $e){
            echo $e->getMessage();
        }catch (\Error $e){
            echo $e->getMessage();
        }
    }
}